package org.jeecg.modules.demo.cwSaleInvoice.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.demo.caiWuSkd.entity.CwSkd;
import org.jeecg.modules.demo.caiWuSkd.service.ICwSkdService;
import org.jeecg.modules.demo.cwSaleInvoice.entity.CwSaleInvoice;
import org.jeecg.modules.demo.cwSaleInvoice.service.ICwSaleInvoiceService;
import org.jeecg.modules.demo.soFeiyong.service.ISoFeiyongService;
import org.jeecg.modules.demo.soFyft.entity.SoFyft;
import org.jeecg.modules.demo.soSaleOrder.entity.SoSaleOrder;
import org.jeecg.modules.demo.soSaleOrder.service.ISoSaleOrderService;
import org.jeecg.modules.demo.soSettlement.entity.SoSettlement;
import org.jeecg.modules.demo.soSettlement.service.ISoSettlementService;
import org.jeecg.modules.demo.util.BigDecimalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Description: 销售发票单
 * @Author: jeecg-boot
 * @Date: 2021-12-15
 * @Version: V1.0
 */
@Api(tags = "销售发票单")
@RestController
@RequestMapping("/sale/cwSaleInvoice")
@Slf4j
public class CwSaleInvoiceController extends JeecgController<CwSaleInvoice, ICwSaleInvoiceService> {
    @Autowired
    private ICwSaleInvoiceService cwSaleInvoiceService;
    @Autowired
    private ICwSkdService cwSkdService;
    @Autowired
    private ISoSettlementService soSettlementService;
    @Autowired
    private ISoSaleOrderService soSaleOrderService;
    @Autowired
    private ISoFeiyongService soFeiyongService;
    @Autowired
    private ISysBaseAPI sysBaseAPI;

    private static final String TITLE = "单据审核";


    private String getMessage(String name, String date) {
        String str = "由【" + name + "】于【" + date + "】发起的收款单需要您的审核，请及时查看！";
        return str;
    }

    /**
     * 分页列表查询
     *
     * @param cwSaleInvoice
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "销售发票单-分页列表查询")
    @ApiOperation(value = "销售发票单-分页列表查询", notes = "销售发票单-分页列表查询")
    @GetMapping(value = "/list")
    @PermissionData(pageComponent="yunxiao/collection/CwSaleInvoiceList")
    public Result<?> queryPageList(CwSaleInvoice cwSaleInvoice,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<CwSaleInvoice> queryWrapper = QueryGenerator.initQueryWrapper(cwSaleInvoice, req.getParameterMap());
        queryWrapper.eq("IS_DELETE", 0);
        Page<CwSaleInvoice> page = new Page<CwSaleInvoice>(pageNo, pageSize);
        IPage<CwSaleInvoice> pageList = cwSaleInvoiceService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    //费用分摊页面
    @GetMapping(value = "/listFyft")
//    @PermissionData(pageComponent="yunxiao/soFyft/SoFyftList")
    public Result<?> queryPageListFyft(CwSaleInvoice cwSaleInvoice,
                                       @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                       HttpServletRequest req) {
        QueryWrapper<CwSaleInvoice> queryWrapper = QueryGenerator.initQueryWrapper(cwSaleInvoice, req.getParameterMap());
        queryWrapper.eq("IS_DELETE", 0);
//		 queryWrapper.ne(true,"FT_JINE",null);
//        queryWrapper.ne(true, "FT_JINE", 0);
        queryWrapper.ne("FT_JINE", 0);
        Page<CwSaleInvoice> page = new Page<CwSaleInvoice>(pageNo, pageSize);
        IPage<CwSaleInvoice> pageList = cwSaleInvoiceService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param cwSaleInvoice
     * @return
     */
    @AutoLog(value = "销售发票单-添加")
    @ApiOperation(value = "销售发票单-添加", notes = "销售发票单-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody CwSaleInvoice cwSaleInvoice) {
        cwSaleInvoiceService.save(cwSaleInvoice);
        return Result.OK("添加成功！");
    }

    //根据发票单生成收款单
    @PostMapping(value = "/addSoSkd")
    public Result<?> addSoSkd(@RequestBody JSONObject jsonObject, HttpServletRequest req) {
        if (cwSaleInvoiceService.addSoSkd(jsonObject,req)) {
            return Result.OK("操作成功！");
        }
        return Result.error("操作失败!");

    }


    /**
     * 编辑
     *
     * @param cwSaleInvoice
     * @return
     */
    @AutoLog(value = "销售发票单-编辑")
    @ApiOperation(value = "销售发票单-编辑", notes = "销售发票单-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody CwSaleInvoice cwSaleInvoice) {
//        cwSaleInvoice.setCreateTime(new Date());
        cwSaleInvoiceService.updateById(cwSaleInvoice);
        return Result.OK("编辑成功!");
    }

    //编辑和使用预收生成收款单
    @PostMapping(value = "/editInvoice")
    public Result<?> editInvoice(@RequestBody JSONObject jsonObject, HttpServletRequest req) {
        if (cwSaleInvoiceService.editInvoice(jsonObject,req)) {
            return Result.OK("操作成功！");
        }
        return Result.error("操作失败!");

    }

    //删除费用分摊
    @PutMapping(value = "/editFyft")
    public Result<?> editFyft(@RequestBody SoFyft soFyft) {
        if (cwSaleInvoiceService.editFyft(soFyft)) {
            return Result.OK("删除成功！");
        }

        return Result.error("删除失败!");

    }

    //审核
    @PutMapping(value = "/editShenhe")
    public Result<?> editShenhe(@RequestBody CwSaleInvoice cwSaleInvoice) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (!cwSaleInvoice.getShName().equals(sysUser.getId())) {
            return Result.error(300, "您不是当前单据的指定审核人！");
        }
        if (cwSaleInvoice.getSoStatus() == 1) {
//            cwSaleInvoice.setShName(sysUser.getRealname());
            cwSaleInvoice.setShTime(new Date());
        } else {
//            cwSaleInvoice.setShName("");
            cwSaleInvoice.setShTime(null);
        }
//        cwSaleInvoice.setCreateTime(new Date());
        cwSaleInvoice.setFtJine(new BigDecimal(0.00));
        cwSaleInvoiceService.updateById(cwSaleInvoice);
        return Result.OK("编辑成功!");
    }

    //假删除销售发票单并修改结算单状态，假删除预开发票单修改销售订单开票金额
    @PutMapping(value = "/editSosettle")
    public Result<?> editSosettle(@RequestBody CwSaleInvoice cwSaleInvoice) {
        try {
            List<CwSkd> sk = cwSkdService.getByfpNo(cwSaleInvoice.getInvoiceNo());
            if (sk.size() > 0) {
                return Result.error(300, "此发票已收款，请先删除对应的收款单！");
            }

            if ("4".equals(cwSaleInvoice.getFplx())) { //发票类型为预开发票4
                SoSaleOrder so = soSaleOrderService.getBysoNo(cwSaleInvoice.getSoNo());
                so.setKpJine(so.getKpJine().subtract(cwSaleInvoice.getSkJine()));
                so.setKpNum(so.getKpNum().subtract(cwSaleInvoice.getFpsl()));
                so.setKjsJine(new BigDecimal(BigDecimalUtil.sub(so.getKjsJine().doubleValue(), cwSaleInvoice.getSkJine().doubleValue())));
                so.setKjskpNum(new BigDecimal(BigDecimalUtil.sub(so.getKjskpNum().doubleValue(), cwSaleInvoice.getFpsl().doubleValue())));
                so.setIsYkp(null);
                SoSettlement soSettlement = soSettlementService.getSoSettleBySosNo(cwSaleInvoice.getSosNo());
                List<SoSettlement> ss = soSettlementService.getHxnoBySosNo(soSettlement.getSosNo());
                if (ss.size() > 0) {
                    return Result.error(300, "此发票下的预结算单已被使用，请先删除对应的红冲单！");
                }
                soSettlementService.removeById(soSettlement);
                soSaleOrderService.updateById(so);
            } else if ("2".equals(cwSaleInvoice.getFplx())) {
                SoSettlement soSettlement = soSettlementService.getSoSettleBySosNo(cwSaleInvoice.getSosNo());
                soSettlement.setIsFpd(0);
                soSettlement.setWkpJine(soSettlement.getWkpJine().add(cwSaleInvoice.getSkJine()));//恢复结算单可开票金额
                soSettlementService.updateById(soSettlement);
            }

            cwSaleInvoiceService.removeById(cwSaleInvoice);

            return Result.OK("删除成功!");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("删除失败");
        }
    }
    //假删除销售发票单并修改结算单状态，假删除预开发票单修改销售订单开票金额
//    @PutMapping(value = "/editSosettle")
//    public Result<?> editSosettle(@RequestBody CwSaleInvoice cwSaleInvoice) {
//        try {
//            //
//            if (cwSaleInvoice.getSosNo() != null && !cwSaleInvoice.getSosNo().isEmpty()) {
//
//                if ("2".equals(cwSaleInvoice.getFplx())) { //发票类型为普通发票2
//
//
//                    List<CwSaleInvoice> cw = cwSaleInvoiceService.getlistBySosNo(cwSaleInvoice.getSosNo());
//                    List<CwSaleInvoice> pufp = new ArrayList<>(); //普通发票集合
//                    List<CwSaleInvoice> ykfp = new ArrayList<>(); //预开发票
//                    SoSettlement soSettlement = soSettlementService.getSoSettleBySosNo(cwSaleInvoice.getSosNo());
//
//                    for (CwSaleInvoice cww : cw) {
//                        if ("4".equals(cww.getFplx())) {
//                            ykfp.add(cww);
//
//                        } else if ("2".equals(cww.getFplx())) {
//                            pufp.add(cww);
//                        }
//                    }
//                    //相同结算单号的普通发票单大于1条时
//                    if (pufp.size() > 1) {
//                        soSettlement.setIsFpd(0);
//                        soSettlement.setWkpJine(soSettlement.getWkpJine().add(cwSaleInvoice.getSkJine()));//恢复结算单可开票金额
//                        soSettlementService.updateById(soSettlement);
//                        cwSaleInvoiceService.removeById(cwSaleInvoice.getId());
//                    } else {   //剩一条普通发票
//                        if (ykfp.size() > 0) {  //如果预开发票存在
//
//                            CwSaleInvoice c = ykfp.get(0);
//                            List<SoSettlement> set = soSettlementService.getByfpNo(c.getInvoiceNo());
//
//                            if (set.size() > 0) {
//                                for (SoSettlement s : set) {
//                                    s.setYkpNo("");
//                                    s.setWkpJine(s.getWkpJine().add(s.getYkpJine()));
//                                    soSettlementService.updateById(s);
//                                }
//                            }
//
//                            c.setSosNo("");
//                            c.setKkpJine(c.getSkJine());
//                            soSettlement.setIsFpd(0);
//                            soSettlement.setWkpJine(soSettlement.getWkpJine().add(cwSaleInvoice.getSkJine()).add(c.getSkJine())); //结算单可开票金额+页面本次开票金额+预开发票未抵扣前的可开票金额
//                            soSettlementService.updateById(soSettlement);
//                            cwSaleInvoiceService.updateById(c);
//                            cwSaleInvoiceService.removeById(cwSaleInvoice.getId());
//                        } else {
//                            soSettlement.setIsFpd(0);
//                            soSettlement.setWkpJine(soSettlement.getWkpJine().add(cwSaleInvoice.getSkJine()));//恢复结算单可开票金额
//                            soSettlementService.updateById(soSettlement);
//                            cwSaleInvoiceService.removeById(cwSaleInvoice.getId());
//                        }
//                    }
//
//                }
//            } else {
//                SoSaleOrder so = soSaleOrderService.getBysoNo(cwSaleInvoice.getSoNo());
//                so.setKpJine(so.getKpJine().subtract(cwSaleInvoice.getSkJine()));
//                so.setIsYkp(null);
//                soSaleOrderService.updateById(so);
//                cwSaleInvoiceService.removeById(cwSaleInvoice.getId());
//            }
//
//            return Result.OK("删除成功!");
//        } catch (Exception e) {
//            log.error(e.getMessage(), e);
//            return Result.error("删除失败");
//        }
//    }

    @GetMapping(value = "/getByfpNo")
    public Result<?> getByfpNo(@RequestParam(name = "invoiceNo", required = true) String invoiceNo) {
        CwSaleInvoice cwSaleInvoice = cwSaleInvoiceService.getByInvoiceNo(invoiceNo);
        if (cwSaleInvoice == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(cwSaleInvoice);
    }
    @GetMapping(value = "/getByfpsyjine")
    public Result<?> getByfpsyjine(@RequestBody CwSaleInvoice cwS) {
        CwSaleInvoice cwSaleInvoice = cwSaleInvoiceService.getByInvoiceNo(cwS.getInvoiceNo());
        if (cwSaleInvoice == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(cwSaleInvoice);
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "销售发票单-通过id删除")
    @ApiOperation(value = "销售发票单-通过id删除", notes = "销售发票单-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        cwSaleInvoiceService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "销售发票单-批量删除")
    @ApiOperation(value = "销售发票单-批量删除", notes = "销售发票单-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.cwSaleInvoiceService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "销售发票单-通过id查询")
    @ApiOperation(value = "销售发票单-通过id查询", notes = "销售发票单-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        CwSaleInvoice cwSaleInvoice = cwSaleInvoiceService.getById(id);
        if (cwSaleInvoice == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(cwSaleInvoice);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param cwSaleInvoice
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CwSaleInvoice cwSaleInvoice) {
        return super.exportXls(request, cwSaleInvoice, CwSaleInvoice.class, "销售发票单");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, CwSaleInvoice.class);
    }

}
